package com.ccp.dev.qbdms.controller;

import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.util.ContextUtil;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.BeanUtils;
import com.ccp.dev.qbdms.model.WQbdFlighttestChild;
import com.ccp.dev.qbdms.service.WQbdFlighttestChildService;
import com.ccp.dev.qbdms.util.ProjectUUIDUtils;
import com.ccp.dev.system.model.SysUser;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.poi.excel.reader.DataEntity;
import com.ccp.dev.core.poi.excel.reader.ExcelReader;
import com.ccp.dev.core.poi.excel.reader.FieldEntity;
import com.ccp.dev.core.poi.excel.reader.TableEntity;
import java.io.PrintWriter;
import net.sf.json.JSONObject;
import java.nio.charset.StandardCharsets;

import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.core.basic.annotion.Action;
import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.ModelMap;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ccp.dev.core.poi.excel.Excel;
import com.ccp.dev.core.poi.excel.editor.IFontEditor;
import com.ccp.dev.core.poi.excel.style.Color;
import com.ccp.dev.core.poi.excel.style.DataFormat;
import com.ccp.dev.core.poi.excel.style.font.BoldWeight;
import com.ccp.dev.core.poi.excel.style.font.Font;
import com.ccp.dev.core.poi.excel.util.ExcelUtil;
import java.util.ArrayList;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.ProcessRunService;

/**
 * 飞行试验子 信息操作处理控制器
 *
 * @author hjx
 * @date 2020-05-07 15:28:26
 */
@Controller
/**
 * 请将此名称添加到日志开关
 */
@Action(customModel = "飞行试验子")
@RequestMapping("/qbdms/wQbdFlighttestChild")
public class WQbdFlighttestChildController extends SysBaseController{
    @Resource
    private WQbdFlighttestChildService wQbdFlighttestChildService;
    @Resource
    private ProcessRunService processRunService;

    /**
     * 功能描述: 跳转到首页
     *
     * @return: java.lang.String
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description="跳转到飞行试验子首页", exectype = "页面跳转日志")
    public String viewList() {
        return "/iframe/link/wQbdFlighttestChildList";
    }
    /**
     * 功能描述: 跳转页面
     *
     * @return: java.lang.String
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/lists")
    @Action(description="跳转页面", exectype = "页面跳转日志")
    public String viewLists() {
        return "wQbdFlighttestChild/list";
    }

    /**
     * 功能描述: 附带检索条件的分页查询
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @ResponseBody
    @Action(description="附带检索条件的分页查询飞行试验子",detail="查询数据信息<#if success>成功<#else></#if>")
    public Object list(HttpServletRequest request) {
        QueryFilter queryFilter = new QueryFilter(request, true);
        //分页数据
        List<WQbdFlighttestChild> pageDatas = wQbdFlighttestChildService.queryList(queryFilter);
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return success(pageDatas, queryFilter.getPageBean().getTotalCount());
    }


    /**
     * 功能描述: 跳转到新增页面
     *
     * @return: java.lang.String
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description="跳转到飞行试验子新增页面", exectype = "页面跳转日志")
    public String viewAdd(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        String runId = RequestUtil.getString(request,"runId");
        modelMap.put("runId",runId);
        return "wQbdFlighttestChild/add";
    }

    /**
     * 功能描述:  数据保存通用方法
     *
     * @param: wQbdFlighttestChild 保存的对象
     * @return: java.lang.Object
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @ResponseBody
    @Action(description="保存飞行试验子数据",detail="<#if isAdd>新增<#else>编辑</#if>飞行试验子数据<#if success>成功<#else>失败</#if>")
    public Object save(@RequestBody WQbdFlighttestChild wQbdFlighttestChild) {
        String id = wQbdFlighttestChild.getId();
        int result;
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("isAdd",true);
            //新增操作
            //新增数据前生成随机Id
            wQbdFlighttestChild.setId(ProjectUUIDUtils.getUUIDFor32());
            result = wQbdFlighttestChildService.add(wQbdFlighttestChild);
        } else {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            //修改操作
            result = wQbdFlighttestChildService.update(wQbdFlighttestChild);
        }
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("save.success") : getResultDataError("save.failure");
    }

    /**
     * 功能描述: 跳转到详情页面
     *
     * @return: java.lang.String
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/particulars")
    @Action(description="跳转到飞行试验子详情页面", exectype = "页面跳转日志")
    public String viewParticulars(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        return "wQbdFlighttestChild/particulars";
    }

    /**
     * 功能描述: 根据主键id获取一条数据的通用查询方法
     *
     * @param: id 参数对象必须是"id"
     * @return: java.lang.Object
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_GET)
    @ResponseBody
    @Action(description="根据主键id查询飞行试验子的一条数据",detail="根据主键id查询飞行试验子的数据<#if success>成功<#else>失败</#if>")
    public Object get(@RequestParam("id") String id) {
        WQbdFlighttestChild wQbdFlighttestChild = wQbdFlighttestChildService.getOneById(id);
        if (null == wQbdFlighttestChild) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("get.failure");
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        return getResultDataSuccess("get.success",wQbdFlighttestChild);
    }

    /**
     * 功能描述: 根据主键ID删除数据的通用删除方法
     *
     * @param: id 参数名称必须是"id"
     * @return: java.lang.Object
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @PostMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description="根据主键ID删除飞行试验子数据",exectype = "删除日志",detail="删除数据信息<#if success>成功<#else>失败</#if>")
    public Object delete(@RequestParam("id") String id) {
        if (StringUtil.isEmpty(id)) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return fail("delete.failure.message");
        }
        int result = wQbdFlighttestChildService.delByIdArray(id.split(","));
        if(result > 0){
            SysAuditThreadLocalHolder.putParamerter("success",true);
        }else{
            SysAuditThreadLocalHolder.putParamerter("success",false);
        }
        return result > 0 ? getResultDataSuccess("delete.success") : getResultDataError("delete.failure");
    }

    /**
     * 功能描述: 跳转到导入页面
     *
     * @return: java.lang.String
     * @auther: hw
     * @date: 2019-12-25 19:21:40
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/import")
    @Action(description="跳转到飞行试验子导入页面", exectype = "页面跳转日志")
    public String viewImport() {
        return "wQbdFlighttestChild/import";
    }

    /**
     * 功能描述: 导出飞行试验子数据信息
     *
     * @param: [request] http请求
     * @return: java.lang.Object
     * @auther: hjx
     * @date: 2020-05-07 15:28:26
     */
    @RequestMapping("/exportData")
    @Action(description="导出飞行试验子数据信息",detail="导出飞行试验子数据信息<#if success>成功<#else></#if>")
    public void export(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String[] id = RequestUtil.getStringAryByStr(request,"id");
        QueryFilter queryFilter = new QueryFilter(request,false);
        if(BeanUtils.isNotEmpty(id) && id.length!=0){
            queryFilter.put("byId",true);
            queryFilter.put("id",id);
        }else{
            queryFilter.put("byId",false);
        }
        SysAuditThreadLocalHolder.putParamerter("success",true);
        Excel excel = new Excel();
        String fileName = "WQbdFlighttestChild";//导出的文件名称
        excel.sheet().sheetName("sheet");// 重命名当前处于工作状态的表的名称
        List<String> titleList = new ArrayList<>();
        titleList.add("主键");
        titleList.add("单位名称");
        titleList.add("奖励总人数");
        titleList.add("金额");
        titleList.add("详细情况");
        titleList.add("排序");
        titleList.add("外键");
        excel.row(0, 0).value(titleList.toArray());
        excel.row(0,0).font(new IFontEditor() {
            // 设置字体
            @Override
            public void updateFont(Font font) {
                font.boldweight(BoldWeight.BOLD);// 粗体
            }
        }).bgColor(Color.GREY_25_PERCENT).width(3500);
        excel.row(0, 1).width(3500);
        excel.row(0, 2).width(3500);
        excel.row(0, 3).width(3500);
        excel.row(0, 4).width(3500);
        //设置列的数据格式
        excel.sheet().setDefaultColumnStyle(0, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(1, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(2, DataFormat.TEXT);
        excel.sheet().setDefaultColumnStyle(3, DataFormat.TEXT);
        ExcelUtil.downloadExcel(wQbdFlighttestChildService.exportExcel(excel,queryFilter), fileName, response);
    }

    /**
     * 导入资源文件
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/importData")
    public void importData(MultipartHttpServletRequest request, HttpServletResponse response) throws Exception{
        MultipartFile multipartFile = request.getFile("file");
        PrintWriter writer = response.getWriter();
        try {
            String fileName = multipartFile.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
            //读取excel文件，并获取每行的数据
            ExcelReader excelReader = new ExcelReader();
            TableEntity excelEntity = excelReader.readFile(multipartFile.getInputStream());
            List<DataEntity> rowDataEntityList = excelEntity.getDataEntityList();

            List<WQbdFlighttestChild> listToInsert = new ArrayList<>();
            for (DataEntity dataEntity : rowDataEntityList) {
                //获取每列的数据
                List<FieldEntity> fieldEntityList = dataEntity.getFieldEntityList();
                WQbdFlighttestChild dataToInsert = new WQbdFlighttestChild();
                int i =0;
                //根据列的顺序，给相应的对象赋值
                for (FieldEntity fieldEntity : fieldEntityList) {
                    //if(i==0){
                    //dataToInsert.setName(fieldEntity.getValue());
                    //}
                    i++;
                }
                dataToInsert.setId(ProjectUUIDUtils.getUUIDFor32());
                listToInsert.add(dataToInsert);
            }
            wQbdFlighttestChildService.addList(listToInsert);
            SysAuditThreadLocalHolder.putParamerter("success",true);
            JSONObject json = JSONObject.fromObject(getResultDataSuccess("operation.success"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1));
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            JSONObject json = JSONObject.fromObject(getResultDataError("operation.failure"));
            writer.print(new String(json.toString().getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1));
        }
    }

    /**
     * 功能描述: 跳转至modify页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/modify")
    @Action(description="跳转到飞行试验子modify页面")
    public String viewModify(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        return "wQbdFlighttestChild/modify";
    }

    /**
     * 功能描述: 跳转至detail页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/detail")
    @Action(description="跳转到飞行试验子detail页面")
    public String viewDetail(HttpServletRequest request,ModelMap modelMap) {
        String id = RequestUtil.getString(request,"id");
        modelMap.put("id",id);
        return "wQbdFlighttestChild/detail";
    }

    /**
     * 功能描述: 启动流程
     */
    @PostMapping("/run")
    @ResponseBody
    @Action(description="启动飞行试验子流程",detail="启动流程<#if success>成功<#else></#if>")
    public Object run(HttpServletRequest request,@RequestBody WQbdFlighttestChild wQbdFlighttestChild){
        SysUser sysUser = (SysUser) ContextUtil.getCurrentUser();
        //实体主键
        String id = wQbdFlighttestChild.getId();
        int isList = RequestUtil.getInt(request,"isList",1);
        ProcessCmd  processCmd = new ProcessCmd();
        //流程Key
        processCmd.setModelKey("test");
        processCmd.setUserAccount(sysUser.getAccount());
        try {
            if(StringUtil.isNotEmpty(id)){
                if(isList == 1){
                    wQbdFlighttestChild = wQbdFlighttestChildService.getOneById(id);
                }
                processCmd.setBusinessKey(id);
                processRunService.startProcess(processCmd);
                wQbdFlighttestChildService.update(wQbdFlighttestChild);
            }else{
                String genId = UUIDUtils.getUUIDFor32();
                processCmd.setBusinessKey(genId);
                wQbdFlighttestChild.setId(genId);
                String tenantId = ContextUtil.getCurrentUserTenantId();
                processRunService.startProcess(processCmd);
                wQbdFlighttestChildService.add(wQbdFlighttestChild);
            }
            SysAuditThreadLocalHolder.putParamerter("success",true);
            return getResultDataSuccess("flow.start.success");
        } catch (Exception e) {
            SysAuditThreadLocalHolder.putParamerter("success",false);
            return getResultDataError("flow.start.failure");
        }
    }

}
